package com.hulman.oms.service;

import com.hulman.oms.bean.Result;
import com.hulman.oms.bean.User;
import com.hulman.oms.bean.WeekReport;
import com.hulman.oms.dao.WeekReportDao;
import com.hulman.oms.exception.IoTException;
import com.hulman.oms.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjusters;
import java.time.temporal.WeekFields;
import java.util.*;

/**
 * @Author: maxwellens
 */
@Service
public class WeekReportService
{
    @Value("${file-home}")
    private String fileHome;
    @Autowired
    private WeekReportDao weekReportDao;
    @Autowired
    private OnlyOfficeService onlyOfficeService;

    public List<WeekReport> findWeekReports(Map<String, Object> map)
    {
        return weekReportDao.findWeekReports(map);
    }

    public Integer findWeekReportsCount(Map<String, Object> map)
    {
        return weekReportDao.findWeekReportsCount(map);
    }

    public Result findWeekReportsResult(Map<String, Object> map)
    {
        Integer page = (Integer) map.get("page");
        Integer limit = (Integer) map.get("limit");
        if (page != null && limit != null)
        {
            map.put("start", (page - 1) * limit);
            map.put("length", limit);
        }
        int count = weekReportDao.findWeekReportsCount(map);
        List<WeekReport> data = weekReportDao.findWeekReports(map);
        return new Result(data, count);
    }

    public WeekReport findWeekReportById(Integer id)
    {
        return weekReportDao.findWeekReportById(id);
    }

    /**
     * 检查工作报告是否已生成
     *
     * @param weekReport
     */
    public void checkWeekReport(WeekReport weekReport)
    {
        Map<String, Object> map = new HashMap<>();
        map.put("year", weekReport.getYear());
        map.put("week", weekReport.getWeek());
        Integer count = weekReportDao.findWeekReportsCount(map);
        if (count > 0)
        {
            throw new IoTException("该周工作报告已生成");
        }
    }

    public void saveWeekReport(WeekReport weekReport)
    {
        if (weekReport.getId() != null && weekReport.getId() != 0)
        {
            weekReportDao.updateWeekReport(weekReport);
        } else
        {
            weekReportDao.insertWeekReport(weekReport);
        }
    }

    public void deleteWeekReportById(Integer id)
    {
        weekReportDao.deleteWeekReportById(id);
    }

    public void deleteWeekReports(int[] ids)
    {
        weekReportDao.deleteWeekReports(ids);
    }

    public void create(WeekReport weekReport) throws IOException
    {
        checkWeekReport(weekReport);
        User user = SubjectUtil.getUser();
        weekReport.setCreateById(user.getId());
        weekReport.setCreateByName(user.getName());
        int year = weekReport.getYear();
        int week = weekReport.getWeek();
        LocalDate firstDayOfYear = LocalDate.of(year, 1, 1);
        LocalDate firstDayOfWeek = firstDayOfYear.with(TemporalAdjusters.firstDayOfYear())
                .with(WeekFields.of(Locale.getDefault()).dayOfWeek(), DayOfWeek.MONDAY.getValue())
                .plusWeeks(week - 1).plusDays(1);
        LocalDate lastDayOfWeek = firstDayOfWeek.plusDays(6);
        Date startDate = Date.from(firstDayOfWeek.atStartOfDay(ZoneId.systemDefault()).toInstant());
        Date endDate = Date.from(lastDayOfWeek.atStartOfDay(ZoneId.systemDefault()).toInstant());
        weekReport.setStartDate(startDate);
        weekReport.setEndDate(endDate);
        weekReport.setState(0);
        //模板生成报告
        if (weekReport.getSource() == 1)
        {
            Map<String, Object> map = new HashMap<>();
            map.put("today", DateUtil.toChineseDate(DateUtil.now()));
            map.put("year", year);
            map.put("week", week);
            map.put("startDate", DateUtil.toChineseDate(startDate));
            map.put("endDate", DateUtil.toChineseDate(endDate));
            InputStream inputStream = Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("template/week-report.docx");
            String fileId = StringUtil.uuid() + ".docx";
            Path filePath = Paths.get(fileHome, fileId);
            OutputStream outputStream = Files.newOutputStream(filePath);
            DocUtil.export(inputStream, outputStream, map);
            weekReport.setFileId(fileId);
        }
        weekReportDao.insertWeekReport(weekReport);
        String fileName = weekReport.getReportCycle() + "养护周报." + FileUtil.parseExtName(weekReport.getFileId());
        onlyOfficeService.create(weekReport.getFileId(), fileName);
    }

    public void submit(Integer id)
    {
        WeekReport weekReport = weekReportDao.findWeekReportById(id);
        weekReport.setState(1);
        weekReport.setEditDate(new Date());
        weekReportDao.updateWeekReport(weekReport);
    }
}
